package com.rc.saas.mini.hlhtcec2.service;

import com.github.dozermapper.core.Mapper;
import com.rc.saas.mini.common.base.TResponse;
import com.rc.saas.mini.component.UidGenerator;
import com.rc.saas.mini.hlhtcec2.config.HlhtOrderStatusEnum;
import com.rc.saas.mini.hlhtcec2.parking.HlhtParkingAssemble;
import com.rc.saas.mini.model.elec.ElecGun;
import com.rc.saas.mini.model.elec.ElecStation;
import com.rc.saas.mini.model.elec.ElecStationPrice;
import com.rc.saas.mini.model.hlht.HlhtOperatorSetting;
import com.rc.saas.mini.model.hlhtsk.HlhtskBizOperator;
import com.rc.saas.mini.model.hlhtsk.HlhtskBizTenant;
import com.rc.saas.mini.model.member.MemberInfo;
import com.rc.saas.mini.model.order.OrderComment;
import com.rc.saas.mini.model.order.OrderInfo;
import com.rc.saas.mini.model.order.OrderInfoExample;
import com.rc.saas.mini.model.car.TenantCarNumber;
import com.rc.saas.mini.service.car.TenantCarNumberService;
import com.rc.saas.mini.service.elec.ElecStationPriceService;
import com.rc.saas.mini.service.hlht.HlhtOperatorSettingService;
import com.rc.saas.mini.service.hlhtsk.HlhtskBizOperatorService;
import com.rc.saas.mini.service.hlhtsk.HlhtskBizTenantService;
import com.rc.saas.mini.service.order.OrderCommentService;
import com.rc.saas.mini.service.order.OrderInfoService;
import com.rc.saas.mini.vo.charge.CommandStartReq;
import com.rc.saas.mini.vo.charge.CommandStopReq;
import com.rc.saas.mini.vo.hlhtcec2.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

/**
 * @author wangzhengwei
 * @create 2021/12/22
 */
@Service
public class HlhtChargeServiceImpl implements HlhtChargeService {
    private static Logger logger = LogManager.getLogger(HlhtChargeServiceImpl.class);
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Autowired
    private Mapper dozerMapper;

    @Autowired
    private UidGenerator uidGenerator;

    @Autowired
    private TenantCarNumberService tenantCarNumberService;

    @Autowired
    private ElecStationPriceService elecStationPriceService;

    @Autowired
    private OrderCommentService orderCommentService;

    @Autowired
    private HlhtskBizTenantService hlhtskBizTenantService;

    @Autowired
    private HlhtskBizOperatorService hlhtskBizOperatorService;

    @Autowired
    private HlhtBiz2NotifyService hlhtBiz2NotifyService;

    @Autowired
    private HlhtOperatorSettingService hlhtOperatorSettingService;

    @Autowired
    private HlhtParkingAssemble hlhtParkingAssemble;

    @Autowired
    private OrderInfoService orderInfoService;

    @Override
    public TResponse assembleStartChargeResult(CommandStartReq commandStartReq, MemberInfo memberInfo, String hlhtOperatorId, ElecStation elecStation, ElecGun elecGun, Integer limitSoc, String accountType, String ticketUsingType, String carNum) {
        logger.info(commandStartReq.getTenantCode() + "-" + hlhtOperatorId + ":HLHT启动充电,memberId:{},gunNo:{},accountType:{}",
                memberInfo.getMemberId(), elecGun.getGunNo(), accountType);

        //生成预充电订单号
        String outOrderNum = uidGenerator.genChargeTenantCode(memberInfo.getTenantCode());

        //创建订单信息
        OrderComment orderComment = new OrderComment();
        orderComment.setTenantCode(memberInfo.getTenantCode());
        //orderInfo.setTenantOperatorCode(elecStation.getTenantOperatorCode());
        //orderInfo.setHlhtTenantCode(hlhtOperatorId);
        orderComment.setHlhtOperatorId(hlhtOperatorId);

        orderComment.setMemberId(commandStartReq.getMemberId());
        orderComment.setElecStationId(commandStartReq.getElecStationId());
        orderComment.setElecPileId(commandStartReq.getElecPileId());
        orderComment.setElecGunId(commandStartReq.getElecGunId());

        orderComment.setOrderNum(outOrderNum);
        orderComment.setOutOrderNum(outOrderNum);

        //默认车牌号添加至订单
        if (carNum == null) {
            TenantCarNumber oriCarNum = tenantCarNumberService.selectDefaultCarNumber(orderComment.getMemberId());
            if (oriCarNum != null) {
                carNum = oriCarNum.getCarArea() + oriCarNum.getCarLetter() + oriCarNum.getCarNum();

            }
        }
        orderComment.setCarNum(carNum);
        //支付的账户类型 支付的账户类型 0个人钱包 1企业钱包
        orderComment.setAccountType(accountType);

        //生成电费列表
        String elecPrices = genPriceList(commandStartReq, elecStation, 0);
        if (StringUtils.isBlank(elecPrices)) {
            logger.error(commandStartReq.getTenantCode() + "-" + hlhtOperatorId + ":找不到计费详情-电费列表:{},:{}", elecStation.getStationNo(), elecGun.getGunNo());
            return TResponse.FAIL("找不到计费详情-电费列表" + elecGun.getGunNo());
        }
        orderComment.setElecPrices(elecPrices);  //基本电费列表

        //生成服务费列表
        String servicePrices = genPriceList(commandStartReq, elecStation, 1);
        if (StringUtils.isBlank(servicePrices)) {
            logger.error(commandStartReq.getTenantCode() + "-" + hlhtOperatorId + ":找不到计费详情-服务费列表:{},:{}", elecStation.getStationNo(), elecGun.getGunNo());
            return TResponse.FAIL("找不到计费详情-服务费列表" + elecGun.getGunNo());
        }

        orderComment.setServicePrices(servicePrices); //服务费列表

        //订单来源 订单来源 0 公众号 1 APP  2小程序 3.刷卡 4.VIN码充电   9.第三方API  默认0
        orderComment.setOrderSource("0");

        //互联互通订单类型以tenant_code为基准,0为自主订单 1反向对接订单 2正向对接订单, 默认0
        orderComment.setHlhtOrderType("2");

        //订单状态 0:用户请求启动
        orderComment.setHlhtOrderStatus(HlhtOrderStatusEnum.HlhtOrderStatus0.getCode());
        orderComment.setCreatedTime(new Date());

        try {
            orderCommentService.insertSelective(orderComment);
        } catch (Exception e) {
            logger.error(commandStartReq.getTenantCode() + "-" + hlhtOperatorId + ":创建订单失败", e);
            return TResponse.FAIL("创建订单失败" + elecGun.getGunNo());
        }

        //推送日志消息
        //MongoChargeProcessLog chargeProcessLog = new MongoChargeProcessLog();
        //chargeProcessLog.setOperatorId(openOperatorId);
        //chargeProcessLog.setCommander(ChargeCmdEnum.USER.getCode());
        //chargeProcessLog.setPlatform(PlatformEnum.JZAPP.getCode());
        //chargeProcessLog.setOutorderNum(outOrderNum);
        //mongoChargeProcessLogAssemble.assembleChargeProcessLog(ChargePhaseEnum.START, chargeProcessLog);
        //logger.info("请求启动充电，创建订单,:{},:{},:{}", outOrderNum, epgNo, connectorId);

        return assembleStartChargeResult(commandStartReq, memberInfo, elecStation, orderComment);

    }

    /**
     * 调用第三方运营商接口
     */
    private TResponse assembleStartChargeResult(CommandStartReq commandStartReq, MemberInfo memberInfo, ElecStation elecStation, OrderComment orderComment){
        //查找运营商信息
        HlhtskBizTenant bizTenant = hlhtskBizTenantService.selectByTenantCodeAndOperatorId(commandStartReq.getTenantCode(), commandStartReq.getHlhtOperatorId(), "1");
        //查找外部运营商信息,申请的互联互通类型,以tenant_code为基准，0反向对接 1正向对接, 默认0
        HlhtskBizOperator bizOperator = hlhtskBizOperatorService.selectByTenantCodeAndOperatorId(commandStartReq.getTenantCode(), commandStartReq.getHlhtOperatorId(), "1");

        //第一步:取Token
        TokenResult tokenResult = hlhtBiz2NotifyService.assembleTokenResult(bizOperator, bizTenant);
        if (tokenResult == null || tokenResult.getSuccStat() != 0) {
            logger.error(bizOperator.getTenantCode() + "-" + bizOperator.getHlhtOperatorId() + ":无法获取Token:{},:{}", commandStartReq.getOutOrderNum(), commandStartReq.getGunNo());
            return TResponse.FAIL("无法启动充电,获取不到Token:" + tokenResult.getFailReason());
        }

        //第2步：取枪状态
        EquipAuthReq equipAuthReq = new EquipAuthReq();
        equipAuthReq.setEquipAuthSeq(uidGenerator.generateEquipAuthSeq(commandStartReq.getTenantCode()));
        equipAuthReq.setConnectorID(commandStartReq.getGunNo());
        EquipAuthResult equipAuthResult = hlhtBiz2NotifyService.assembleEquipAuthResult(equipAuthReq, tokenResult, bizOperator, bizTenant);

        if (equipAuthResult == null || equipAuthResult.getSuccStat() != 0) {
            logger.error(bizOperator.getTenantCode() + "-" + bizOperator.getHlhtOperatorId() + ":无法获取枪状态:{},:{}", commandStartReq.getOutOrderNum(), commandStartReq.getGunNo());
            return TResponse.FAIL("未插枪:" + equipAuthResult.getFailReason());
        }

        //第3步：取价格
        EquipBusinessPolicyReq equipBusinessPolicyReq = new EquipBusinessPolicyReq();
        equipBusinessPolicyReq.setEquipBizSeq(uidGenerator.generateEquipBizSeq(commandStartReq.getTenantCode()));
        equipBusinessPolicyReq.setConnectorID(commandStartReq.getGunNo());
        EquipBusinessPolicyResult equipBusinessPolicyResult = hlhtBiz2NotifyService.assembleEquipBusinessPolicyResult(equipBusinessPolicyReq, tokenResult, bizOperator, bizTenant);

        if (equipBusinessPolicyResult == null || equipBusinessPolicyResult.getSuccStat() != 0) {
            logger.error(bizOperator.getTenantCode() + "-" + bizOperator.getHlhtOperatorId() + ":无法获价格策略:{},:{}", commandStartReq.getOutOrderNum(), commandStartReq.getGunNo());
            return TResponse.FAIL("无法获价格策略:" + equipBusinessPolicyResult.getFailReason());
        }

        //遍历检查是否有0价格
        List <PolicyInfo> policyInfos = equipBusinessPolicyResult.getPolicyInfos();
        for (PolicyInfo policyInfo : policyInfos) {
            //如果电价等于或小于0，禁止启动
            if (policyInfo.getElecPrice().compareTo(BigDecimal.ZERO) == 0 || policyInfo.getElecPrice().compareTo(BigDecimal.ZERO) == -1) {
                logger.error(bizOperator.getTenantCode() + "-" + bizOperator.getHlhtOperatorId() + ":不正确的电价(等于或小于0):{},:{},:{}", commandStartReq.getOutOrderNum(), commandStartReq.getGunNo(), policyInfo.getElecPrice());
                return TResponse.FAIL("不正确的电价(等于或小于0)");
            }

            //如果服务费等于或小于0，禁止启动
            if (policyInfo.getSevicePrice().compareTo(BigDecimal.ZERO) == 0 || policyInfo.getSevicePrice().compareTo(BigDecimal.ZERO) == -1) {
                logger.error(bizOperator.getTenantCode() + "-" + bizOperator.getHlhtOperatorId() + ":不正确的服务费(等于或小于0):{},:{},:{}", commandStartReq.getOutOrderNum(), commandStartReq.getGunNo(), policyInfo.getSevicePrice());
                return TResponse.FAIL("不正确的服务费(等于或小于0)");
            }
        }

        //第5步：启动充电
        StartChargeReq startChargeReq = new StartChargeReq();
        startChargeReq.setStartChargeSeq(orderComment.getOutOrderNum());
        startChargeReq.setConnectorID(commandStartReq.getGunNo());
        startChargeReq.setQRCode("");
        startChargeReq.setCarPlateNo(orderComment.getCarNum());

        //下达指令
        StartChargeResult startChargeResult = hlhtBiz2NotifyService.assembleStartChargeResult(startChargeReq, tokenResult, bizOperator, bizTenant);
        if (startChargeResult == null || startChargeResult.getSuccStat() != 0) {
            logger.error(bizOperator.getTenantCode() + "-" + bizOperator.getHlhtOperatorId() + ":请求启动充电失败,:{},:{}", commandStartReq.getOutOrderNum(), commandStartReq.getGunNo());
            return TResponse.FAIL("请求启动充电失败");
        }

        //第6步：停车减免入场信息

        HlhtOperatorSetting hlhtOperatorSetting = hlhtOperatorSettingService.selectByTenantCodeAndOperatorId(bizOperator.getTenantCode(), bizOperator.getHlhtOperatorId());
        //open_out_type对接出场方式 0无 1道闸 2其它 默认0
        if (hlhtOperatorSetting.getOpenOutType().equals("1")) {
            notification_start_charge_carnum(orderComment, tokenResult, bizOperator, bizTenant);
        }

        TResponse tResponse = TResponse.SUCCESS();

        //StartChargeResult转换为AppStartChargeResult
        WxStartChargeResult appStartChargeResult = dozerMapper.map(startChargeResult, WxStartChargeResult.class);
        tResponse.put(appStartChargeResult);

        return tResponse;

    }

    public TResponse assembleEquipChargeStatusResult(CommandStartReq commandStartReq){
        //查找运营商信息
        HlhtskBizTenant bizTenant = hlhtskBizTenantService.selectByTenantCodeAndOperatorId(commandStartReq.getTenantCode(), commandStartReq.getHlhtOperatorId(), "1");
        //查找运营商信息,申请的互联互通类型,以tenant_code为基准，0反向对接 1正向对接, 默认0
        HlhtskBizOperator bizOperator = hlhtskBizOperatorService.selectByTenantCodeAndOperatorId(commandStartReq.getTenantCode(), commandStartReq.getHlhtOperatorId(), "1");

        //第1步：取Token
        TokenResult tokenResult = hlhtBiz2NotifyService.assembleTokenResult(bizOperator, bizTenant);
        if (tokenResult == null || tokenResult.getSuccStat() != 0) {
            logger.error(bizOperator.getTenantCode() + "-" + bizOperator.getHlhtOperatorId() + ":无法获取Token:{},:{}", commandStartReq.getOutOrderNum(), commandStartReq.getGunNo());
            return TResponse.FAIL("无法启动充电,获取不到Token:" + tokenResult.getFailReason());
        }

        //下达指令
        EquipChargeStatusReq equipChargeStatusReq = new EquipChargeStatusReq();
        equipChargeStatusReq.setStartChargeSeq(commandStartReq.getOutOrderNum());
        EquipChargeStatusResult equipChargeStatusResult = hlhtBiz2NotifyService.assembleEquipChargeStatusResult(equipChargeStatusReq, tokenResult, bizOperator, bizTenant);
        if (equipChargeStatusResult == null) {
            logger.error(bizOperator.getTenantCode() + "-" + bizOperator.getHlhtOperatorId() + ":查询充电状态为空:{},:{}", commandStartReq.getOutOrderNum(), commandStartReq.getGunNo());
            return TResponse.FAIL("查询充电状态为空:" + tokenResult.getFailReason());
        }

        WxEquipChargeStatusResult wxEquipChargeStatusResult = dozerMapper.map(equipChargeStatusResult, WxEquipChargeStatusResult.class);
        //从order_info表查找订单
        OrderInfo orderInfo = orderInfoService.selectOrderByOutOrderNum(commandStartReq.getOutOrderNum());
        if (orderInfo != null){
            if (orderInfo.getStatus().equals("1")){
                wxEquipChargeStatusResult.setStartTime(sdf.format(orderInfo.getStartTime()));
                SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
                formatter.setTimeZone(TimeZone.getTimeZone("GMT+0"));
                Date date = new Date(System.currentTimeMillis() - orderInfo.getStartTime().getTime());
                wxEquipChargeStatusResult.setDuration(formatter.format(date));

                wxEquipChargeStatusResult.setCarNum(orderInfo.getCarNum());
                logger.info(orderInfo.getHlhtOperatorId() + ":" + wxEquipChargeStatusResult.getCarNum() + ":充电时长计算:{}", wxEquipChargeStatusResult.getDuration());
                wxEquipChargeStatusResult.setOrderStatus(orderInfo.getStatus());
                //本次采样时间
                equipChargeStatusResult.setEndTime(sdf.format(System.currentTimeMillis()));
            } else if (orderInfo.getStatus().equals("2")){//充电完成，从数据库取
                //CEC标准
                //1: 空闲；
                //2: 占用（未充电）；
                //3: 占用（充电中）；
                //4: 占用（预约锁定）；
                //255: 故障
                wxEquipChargeStatusResult.setConnectorStatus(1);
                wxEquipChargeStatusResult.setOrderStatus(orderInfo.getStatus());
                //目前没有收集电流和电压参数
                wxEquipChargeStatusResult.setCurrentA(new BigDecimal("0"));
                wxEquipChargeStatusResult.setVoltageA(new BigDecimal("0"));

            }

            if (orderInfo.getCarNum() != null){
                wxEquipChargeStatusResult.setCarNum(orderInfo.getCarNum());
            }
        }
        wxEquipChargeStatusResult.setTotalPower(wxEquipChargeStatusResult.getTotalPower() == null ? BigDecimal.ZERO
                : wxEquipChargeStatusResult.getTotalPower().setScale(3, BigDecimal.ROUND_HALF_UP));
        logger.info(bizOperator.getTenantCode() + "-" + bizOperator.getHlhtOperatorId() + ":本次采样:{}", equipChargeStatusResult.toString());
        if (orderInfo!=null){
            wxEquipChargeStatusResult.setOrderId(orderInfo.getOrderId());
        }
        return TResponse.SUCCESS_DATA(wxEquipChargeStatusResult);
    }

    /**
     * 停车减免
     * @param orderComment
     */
    private void notification_start_charge_carnum(OrderComment orderComment, TokenResult tokenResult, HlhtskBizOperator bizOperator, HlhtskBizTenant bizTenant) {
        NotifyCarNumReq notifyCarNumReq = new NotifyCarNumReq();
        notifyCarNumReq.setStartChargeSeq(orderComment.getOutOrderNum());
        notifyCarNumReq.setStartTime(sdf.format(new Date()));

        //TenantCarNumber defultCarNum = tenantCarNumberService.selectDefaultCarNumber(memberInfo);
        //if (defultCarNum != null && StringUtils.isNotBlank(defultCarNum.getCarNum())) {
        //    notifyCarNumReq.setCarnum(defultCarNum.getCarNum());
        //}
        TenantCarNumber tenantCarNumber = tenantCarNumberService.selectDefaultCarNumber(orderComment.getMemberId());
        if (tenantCarNumber != null) {
            String oriCarNum = tenantCarNumber.getCarArea() + tenantCarNumber.getCarLetter() + tenantCarNumber.getCarNum();
            notifyCarNumReq.setCarnum(oriCarNum);


            //notifyCarNumReq.setCarnum("京A888888");
            logger.info("notification_start_charge_carnum 车牌号,:{},:{}", orderComment.getOutOrderNum(), oriCarNum);

            int result = hlhtParkingAssemble.assembleNotifyCarNumResult(notifyCarNumReq, tokenResult, bizOperator, bizTenant);
            if (result == 0) {
                logger.info(bizTenant.getTenantCode() + "-" + bizTenant.getHlhtOperatorId() + ":停车减免成功:{},:{}", notifyCarNumReq.getStartChargeSeq(), oriCarNum);
            } else {
                logger.info(bizTenant.getTenantCode() + "-" + bizTenant.getHlhtOperatorId() + ":停车减免异常:{},:{}", notifyCarNumReq.getStartChargeSeq(), oriCarNum);
            }
        }
    }

    @Override
    public TResponse assembleStopChargeResult(CommandStopReq commandStopReq) {
        //推送日志消息
        //MongoChargeProcessLog chargeProcessLog = new MongoChargeProcessLog();
        //switch (stopType) {
        //    case STOP:
        //        chargeProcessLog.setOperatorId(openOperatorId);
        //        chargeProcessLog.setCommander(ChargeCmdEnum.USER.getCode());
        //        chargeProcessLog.setPlatform(PlatformEnum.JZAPP.getCode());
        //        chargeProcessLog.setOutorderNum(startChargeSeq);
        //        mongoChargeProcessLogAssemble.assembleChargeProcessLog(ChargePhaseEnum.STOP, chargeProcessLog);
        //        break;
        //    case NOT_ENOUGH_STOP:
        //        chargeProcessLog.setOperatorId(openOperatorId);
        //        chargeProcessLog.setCommander(ChargeCmdEnum.USER.getCode());
        //        chargeProcessLog.setPlatform(PlatformEnum.JZAPP.getCode());
        //        chargeProcessLog.setOutorderNum(startChargeSeq);
        //        mongoChargeProcessLogAssemble.assembleChargeProcessLog(ChargePhaseEnum.NOT_ENOUGH_STOP, chargeProcessLog);
        //        break;
        //}

        //查找运营商信息
        HlhtskBizTenant bizTenant = hlhtskBizTenantService.selectByTenantCodeAndOperatorId(commandStopReq.getTenantCode(), commandStopReq.getHlhtOperatorId(), "1");
        //查找运营商信息,申请的互联互通类型,以tenant_code为基准，0反向对接 1正向对接, 默认0
        HlhtskBizOperator bizOperator = hlhtskBizOperatorService.selectByTenantCodeAndOperatorId(commandStopReq.getTenantCode(), commandStopReq.getHlhtOperatorId(), "1");

        //第1步：取Token
        TokenResult tokenResult = hlhtBiz2NotifyService.assembleTokenResult(bizOperator, bizTenant);
        if (tokenResult == null || tokenResult.getSuccStat() != 0) {
            logger.error(bizOperator.getTenantCode() + "-" + bizOperator.getHlhtOperatorId() + ":无法获取Token:{},:{}", commandStopReq.getOutOrderNum(), commandStopReq.getGunNo());
            return TResponse.FAIL("无法结束充电,获取不到Token");
        }

        //下达指令
        StopChargeReq stopChargeReq = new StopChargeReq();
        stopChargeReq.setStartChargeSeq(commandStopReq.getOutOrderNum());
        stopChargeReq.setConnectorID(commandStopReq.getGunNo());
        StopChargeResult stopChargeResult = hlhtBiz2NotifyService.assembleStopChargeResult(stopChargeReq, tokenResult, bizOperator, bizTenant);
        if (stopChargeResult == null || stopChargeResult.getSuccStat() != 0) {
            logger.error(bizOperator.getTenantCode() + "-" + bizOperator.getHlhtOperatorId() + ":请求停止充电失败,:{},:{}", commandStopReq.getOutOrderNum(), commandStopReq.getGunNo());
            return TResponse.FAIL("请求停止充电失败");
        }

        OrderInfo orderInfo = orderInfoService.selectOrderByOutOrderNum(stopChargeResult.getStartChargeSeq());

        //正向对接时,第三方运营商的订单状态,订单状态,0:用户请求启动 1:充电中(收到启动回调) 2:用户请求停止/其它原因停止 3:已停止(收到停止回调) 4:已结算(收到结算推送) 5:挂单(2分钟内未收到停止回调或结算推送) 6:无效订单
        if (orderInfo.getHlhtOrderStatus().equals(HlhtOrderStatusEnum.HlhtOrderStatus4.getCode())) {
            logger.info(bizOperator.getTenantCode() + "-" + bizOperator.getHlhtOperatorId() + ":订单已经结算,:{},:{}", stopChargeResult.getStartChargeSeq(), stopChargeResult.getStartChargeSeqStat());
        } else {
            //OrderInfo updateOrderInfo = new OrderInfo();
            ////订单状态 2:用户请求停止
            //updateOrderInfo.setHlhtOrderStatus(HlhtOrderStatusEnum.HlhtOrderStatus2.getCode());
            //
            //OrderInfoExample example = new OrderInfoExample();
            //example.createCriteria().andOutOrderNumEqualTo(stopChargeResult.getStartChargeSeq());
            //orderInfo.setHlhtOrderStatus(HlhtOrderStatusEnum.HlhtOrderStatus2.getCode());
            orderInfoService.updateByPrimaryKeySelective(orderInfo);
            //orderInfoService.updateByExampleSelective(updateOrderInfo, example);

            logger.info(bizOperator.getTenantCode() + "-" + bizOperator.getHlhtOperatorId() + ":成功停止充电，已更新订单状态,:{},:{}", stopChargeResult.getStartChargeSeq(),
                    stopChargeResult.getStartChargeSeqStat());
        }

        WxStopChargeResult appStopChargeResult = dozerMapper.map(stopChargeResult, WxStopChargeResult.class);
        if (appStopChargeResult.getFailReason() == null) {
            appStopChargeResult.setFailMsg(0);
        } else {
            appStopChargeResult.setFailMsg(appStopChargeResult.getFailReason());
        }

        return TResponse.SUCCESS_DATA(appStopChargeResult);
    }

    /**
     * 获取电费/服务费 列表
     * @param priceType 0基本电费，1服务费
     */
    private String genPriceList(CommandStartReq commandStartReq, ElecStation elecStation, int priceType) {
        logger.info(commandStartReq.getTenantCode() + "-" + commandStartReq.getHlhtOperatorId() + ":获取电费/服务费列表,:{},:{},:{}", elecStation.getStationNo(), commandStartReq.getGunNo(), priceType);

        //获取电价
        //得到桩群服务费,充电费率
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        List<ElecStationPrice> elecStationPrices = elecStationPriceService.listStationPricesByStationId(commandStartReq.getTenantCode(), commandStartReq.getHlhtOperatorId(),
                elecStation.getElecStationId());

        StringBuffer sb = new StringBuffer();
        if (priceType == 0) {//0 基本电费
            for (ElecStationPrice stationPrice : elecStationPrices) {
                sb.append(sdf.format(stationPrice.getBeginTime())).append("~")
                        .append(sdf.format(stationPrice.getEndTime())).append(" ")
                        .append(stationPrice.getElecPrice()).append("元/度")
                        .append("#");
            }
        } else {//1服务费
            for (ElecStationPrice price : elecStationPrices) {
                sb.append(sdf.format(price.getBeginTime())).append("~")
                        .append(sdf.format(price.getEndTime())).append(" ")
                        .append(price.getServicePrice()).append("元/度")
                        .append("#");
            }
        }

        return sb.toString().substring(0, sb.length() - 1);
    }

    @Override
    public String getCurrDataSoc(ElecGun gun, String tenantCode, String hlhtOperatorId) {
        //查找运营商信息
        HlhtskBizTenant bizTenant = hlhtskBizTenantService.selectByTenantCodeAndOperatorId(tenantCode, hlhtOperatorId, "1");
        //查找运营商信息,申请的互联互通类型,以tenant_code为基准，0反向对接 1正向对接, 默认0
        HlhtskBizOperator bizOperator = hlhtskBizOperatorService.selectByTenantCodeAndOperatorId(tenantCode, hlhtOperatorId, "1");

        //第1步：取Token
        TokenResult tokenResult = hlhtBiz2NotifyService.assembleTokenResult(bizOperator, bizTenant);

        OrderInfoExample orderInfoExample = new OrderInfoExample();
        orderInfoExample.createCriteria().andStatusEqualTo("1").andElecGunIdEqualTo(gun.getElecGunId());
        orderInfoExample.setOrderByClause("created_time desc");
        OrderInfo orderInfo = orderInfoService.selectByExample(orderInfoExample).stream().findFirst().orElseGet(() -> null);
        if (orderInfo != null) {
            if (tokenResult == null || tokenResult.getSuccStat() != 0) {
                logger.error(bizOperator.getTenantCode() + "-" + bizOperator.getHlhtOperatorId() + ":无法获取Token:{},:{}", orderInfo.getOutOrderNum(), gun.getGunNo());
                return "0";
            }
            //下达指令
            EquipChargeStatusReq equipChargeStatusReq = new EquipChargeStatusReq();
            equipChargeStatusReq.setStartChargeSeq(orderInfo.getOutOrderNum());
            EquipChargeStatusResult equipChargeStatusResult = hlhtBiz2NotifyService.assembleEquipChargeStatusResult(equipChargeStatusReq, tokenResult, bizOperator, bizTenant);
            if (equipChargeStatusResult == null) {
                logger.error(bizOperator.getTenantCode() + "-" + bizOperator.getHlhtOperatorId() + ":查询充电状态为空:{},:{}", orderInfo.getOutOrderNum(), gun.getGunNo());
                return "0";
            }
            //取整
            return equipChargeStatusResult.getSoc() != null ? String.valueOf(equipChargeStatusResult.getSoc().setScale(0, BigDecimal.ROUND_DOWN)) : "0";
        }
        return "0";
    }
}
